/**
 * @ngdoc overview
 * @name  activity.controllers
 * @description
 *  活动模板控制器
 */
angular.module('activity.controllers', [])

// 全部活动
.controller('ActivityIndexCtrl', function($scope, $state, $ionicScrollDelegate, ActivityList ) {
  $scope.stateName = $state.$current.name;

  $scope.activity = new ActivityList({
    type: 'all'
  });

  $scope.load = function() {
    $scope.activity.load()
    .success(function() {
      $ionicScrollDelegate.resize();
    });
  };

  $scope.reload = function() {
    $scope.activity.reload()
    .finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

  $scope.load();
})

// 我参加的
.controller('ActivityJoinCtrl', function($scope, $state, $ionicScrollDelegate, ActivityList) {
  $scope.stateName = $state.$current.name;

  $scope.activity = new ActivityList({
    type: 'me'
  });

  $scope.load = function() {
    $scope.activity.load()
    .success(function() {
      $ionicScrollDelegate.resize();
    });
  };

  $scope.reload = function() {
    $scope.activity.reload()
    .finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

  $scope.load();
})

// 活动详情
.controller('ActivityViewCtrl', function($scope, $timeout, $stateParams, $ionicScrollDelegate, $ionicLoading, Activity) {
  $scope.activityId = $stateParams.id;

  // 获取活动数据
  $ionicLoading.show();
  Activity.view($stateParams)
  .success(function(res) {
    if(res.isSuccess) {
      $scope.item = res.data;
    }
  })
  .finally($ionicLoading.hide);

  $scope.toggleOpen = true;
  $scope.toggleView = function() {
    $scope.toggleOpen = !$scope.toggleOpen;
    $timeout(function() {
      $ionicScrollDelegate.resize();
    }, 100)
  };

  // 打开地图
  $scope.openMap = function() {
    window.location.href = 'http://api.map.baidu.com/place/search?query=' + $scope.item.address + '&region=' + $scope.item.address + '&output=html';
    // window.location.href = 'http://apis.map.qq.com/uri/v1/search?region=' + $scope.item.address + '&keyword=' + $scope.item.address;
  };

  // if($scope.card.address) {
  //   $scope.location = {
  //     latitude: 0, // 纬度，浮点数，范围为90 ~ -90
  //     longitude: 0, // 经度，浮点数，范围为180 ~ -180。
  //     name: $scope.card.corpname, // 位置名
  //     address: $scope.card.address, // 地址详情说明
  //     scale: 15, // 地图缩放级别,整形值,范围从1~28。默认为最大
  //     infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
  //   };

  //   Namecard.getLocation($scope.card.address)
  //   .success(function(res) {
  //     if(res.status === 0) {
  //       $scope.location.latitude = +res.result.location.lat;
  //       $scope.location.longitude = +res.result.location.lng;
  //     }
  //   });

  //   $scope.openLocation = function() {
  //     External.openLocation($scope.location);
  //   };
  // }
})

// 活动报名/编辑报名数据
.controller('ActivityCreateCtrl', function($scope, $state, $stateParams, $ionicLoading, IbPopup, User, Activity) {
  $scope.fields = [];
  $scope.form = {};
  $scope.note = {};

  // 获取报名字段
  $ionicLoading.show();
  Activity.formField($stateParams)
  .success(function(res) {
    if(res.isSuccess) {
      $scope.fields = res.data.formdata;
      
      // 填充表单模型的默认值
      // 如果是报名，设置当前用户的姓名和手机为默认
      if(!$stateParams.formdataid) {
        $scope.form[$scope.fields[0].fieldname] = User.user.realname;
        $scope.form[$scope.fields[1].fieldname] = User.user.mobile;

        // 因为PC默认是关闭状态，统一“是否” 类型默认值为 false
        angular.forEach($scope.fields, function(field) {
          if(field.fieldtype == '3') {
            $scope.form[field.fieldname] = false;
          }
        });
      } else {
        // 如果是编辑报名数据，则先还原原始值
        angular.forEach($scope.fields, function(field) {
          // “是否” 类型要特殊处理一下
          if(field.fieldtype == '3') {
            if(field.value === '0.') {
              $scope.form[field.fieldname] = false;
            } else {
              $scope.form[field.fieldname] = true;
              $scope.note[field.fieldname] = field.value.slice(2);
            }
          } else {
            $scope.form[field.fieldname] = field.value;
          }
        });
      }
    } else {
      IbPopup.alert({ title: res.msg });
    }
  })
  .finally($ionicLoading.hide);

  // 保存\更新报名数据
  $scope.save = function() {
    var data = angular.extend({}, $scope.form);
    var method = 'createSignUp';

    // 增加活动id，用户id等字段
    data.moduleid = $stateParams.id;
    if($stateParams.formdataid) {
      method = 'updateSignUp';
      data.formdataid = $stateParams.formdataid;
    }

    // 当开启“是否”开关时，将备注值作为该字段值保存下来
    angular.forEach($scope.fields, function(field) {
      // “是否”类型时
      if(field.fieldtype == '3') {
        if($scope.form[field.fieldname]) {
          data[field.fieldname] = '1.' + ($scope.note[field.fieldname] || '');
        } else {
          data[field.fieldname] = '0.';
        }
      }
    });

    $ionicLoading.show();
    Activity[method](data)
    .success(function(res) {
      if(res.isSuccess) {
        $state.go('activity.info', $stateParams);
      } else {
        IbPopup.alert({ title: res.msg });
      }
    })
    .finally($ionicLoading.hide);
  };
})

// 查看报名详情
.controller('ActivityInfoCtrl', function($scope, $stateParams, $ionicLoading, Utils, IbPopup, Activity) {
  $scope.activityId = $stateParams.id;

  $ionicLoading.show();
  Activity.signUpList($stateParams)
  .success(function(res) {
    if(res.isSuccess) {
      $scope.infos = res.data;
    } else {
      IbPopup.alert({ title: res.msg });
    }
  })
  .finally($ionicLoading.hide);

  // 删除报名数据
  $scope.removeItem = function(info) {
    IbPopup.confirm({ title: '确定要删除该报名信息？' })
    .then(function(ok) {
      if(ok) {
        $ionicLoading.show();
        Activity.deleteSignUp({
          moduleid: $stateParams.id,
          formdataid: info.formdataid
        })
        .success(function(res) {
          if(res.isSuccess) {
            Utils.eliminate($scope.infos, info);
          } else {
            IbPopup.alert({ title: res.msg });
          }
        })
        .finally($ionicLoading.hide);
      }
    });
  };
})

// 查看活动安排
.controller('ActivityArrangeCtrl', function($scope, $stateParams, $ionicLoading, IbPopup, Activity) {

  $ionicLoading.show();
  Activity.arrangeList($stateParams)
  .success(function(res) {
    if(res.isSuccess) {
      $scope.fields = res.data.formdata;
      $scope.activity = res.data.activity;
    } else {
      IbPopup.alert({ title: res.msg });
    }
  })
  .finally($ionicLoading.hide);

});
